<template>
  <div class="header-container">
    <div class="wrapper">
      <!-- logo -->
      <div class="left-wrapper v-link selected">
        <img alt="" style="width: 50px" width="50" height="50" src="~assets/images/logo.png">
        <span class="text">预约挂号统一平台</span>
      </div>
      <!-- 搜索框 -->
      <div class="search-wrapper">
        <div class="hospital-search animation-show">
          <el-autocomplete
            class="search-input small"
            prefix-icon="el-icon-search"
            v-model="state"
            :fetch-suggestions="querySearchAsync"
            placeholder="点击输入医院名称"
            @select="handleSelect"
          >
            <span slot="suffix" class="search-btn v-link highlight clickable selected">搜索 </span>
          </el-autocomplete>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="right-wrapper">
        <span class="v-link clickable">帮助中心</span>
        <span class="v-link clickable" v-if="name === ''" id="loginDialog" @click="showLogin()">登录/注册</span>
        <el-dropdown v-if="name !== ''" @command="loginMenu">
          <span class="el-dropdown-link">
            {{ name }}
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu class="user-name-wrapper" slot="dropdown">
            <!-- “command”的值为下拉列表的访问路径 -->
            <el-dropdown-item command="/user">实名认证</el-dropdown-item>
            <el-dropdown-item command="/order">挂号订单</el-dropdown-item>
            <el-dropdown-item command="/patient">就诊人管理</el-dropdown-item>
            <el-dropdown-item command="/logout" divided>退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <!-- 登录弹出层 -->
    <el-dialog :visible.sync="dialogUserFormVisible" style="text-align: left;" :modal-append-to-body='false' top="50px" width="960px" @close="closeDialog()">
      <div class="container">
        <!-- 手机登录 #start -->
        <div class="operate-view" v-if="dialogAttr.showLoginType === 'phone'">
          <!-- 解决dialog布局错乱问题 -->
          <div class="wrapper" style="min-width: 0;flex-direction: column">
            <div class="mobile-wrapper" style="position: static;">
              <span class="title">{{ dialogAttr.labelTips }}</span>
              <el-form>
                <el-form-item>
                  <el-input v-model="dialogAttr.inputValue" :placeholder="dialogAttr.placeholder" :maxlength="dialogAttr.maxlength" class="input v-input">
                    <span slot="suffix" class="sendText v-link" v-if="dialogAttr.second > 0">{{ dialogAttr.second }}s </span>
                    <span slot="suffix" class="sendText v-link highlight clickable selected" v-if="dialogAttr.second === 0" @click="getCodeFun">重新发送 </span>
                  </el-input>
                </el-form-item>
              </el-form>
              <div class="send-button v-button" @click="btnClick"> {{ dialogAttr.loginBtn }}</div>
            </div>
            <div class="bottom">
              <div class="wechat-wrapper" @click="weixinLogin">
                <span class="iconfont icon iconweixin"/>
              </div>
              <span class="third-text"> 第三方账号登录 </span>
            </div>
          </div>
        </div>
        <!-- 手机登录 #end -->

        <!-- 微信登录 #start -->
        <div class="operate-view"  v-if="dialogAttr.showLoginType === 'weixin'" >
          <div class="wrapper wechat" style="height: 400px; min-width: 0; flex-direction: column">
            <div>
              <div id="weixinLogin"></div>
            </div>
            <div class="bottom wechat" style="margin-top: -80px;">
              <div class="phone-container">
                <div class="phone-wrapper"  @click="phoneLogin">
                  <span class="iconfont icon el-icon-phone"></span>
                </div>
                <span class="third-text"> 手机短信验证码登录 </span>
              </div>
            </div>
          </div>
        </div>
        <!-- 微信登录 #end -->

        <div class="info-wrapper">
          <div class="code-wrapper">
            <div>
              <img alt="" src="//img.114yygh.com/static/web/code_login_wechat.png" class="code-img">
              <div class="code-text">
                <span class="iconfont icon"/>
                微信扫一扫关注
              </div>
              <div class="code-text">
                “快速预约挂号”
              </div>
            </div>
            <div class="wechat-code-wrapper">
              <img alt="" src="//img.114yygh.com/static/web/code_app.png" class="code-img">
              <div class="code-text">
                扫一扫下载
              </div>
              <div class="code-text">
                “预约挂号”APP
              </div>
            </div>
          </div>
          <div class="slogan">
            <div>xxxxxx官方指定平台</div>
            <div>快速挂号 安全放心</div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import cookie from 'js-cookie'
import Vue from 'vue'

import userInfo from "@/api/custom/userInfo";
import msm from "@/api/msm/msm"
import hospital from "@/api/hosp/hospital";
import wechat from "@/api/wechat/wechat";

const  defaultDialogAttr = {
  showLoginType: 'phone', // 控制手机登录与微信登录切换

  labelTips: '手机号码', // 输入框提示

  inputValue: '', // 输入框绑定对象
  placeholder: '请输入您的手机号', // 输入框placeholder
  maxlength: 11, // 输入框长度控制

  loginBtn: '获取验证码', // 登录按钮或获取验证码按钮文本

  sending: true,      // 是否可以发送验证码
  second: -1,        // 倒计时间  second>0 : 显示倒计时 second=0 ：重新发送 second=-1 ：什么都不显示
  clearSmsTime: null  // 倒计时定时任务引用 关闭登录层清除定时任务
}

export default {
  name: "myHeader",
  created() {
    this.showInfo()
  },
  mounted() {
    // 注册全局登录事件
    window.loginEvent = new Vue()
    // 触发事件，，显示 登录层
    loginEvent.$on('loginDialogEvent', () => {
      document.getElementById('loginDialog').click()
    })

    // 初始化微信js
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
    document.body.appendChild(script)

    // 微信登录回调处理
    let self = this
    window['loginCallback'] = (name, token, openid) => {
      self.loginCallback(name, token, openid)
    }
  },
  data() {
    return {
      userInfo: {
        phone: '',
        code: '',
        openid: ''
      },
      state: '',
      dialogAttr: defaultDialogAttr,
      dialogUserFormVisible: false,
      name: ''
    }
  },
  methods: {
    // 绑定登录或验证码获取
    btnClick() {
      if(this.dialogAttr.loginBtn === '获取验证码'){
        this.userInfo.phone = this.dialogAttr.inputValue
        console.log(this.userInfo)
        this.getCodeFun()
      }else {
        this.login()
      }
    },
    querySearchAsync(queryString, cb) {
      if(queryString === ''){
        return
      }
      hospital.getByHosname(queryString).then(res => {
        for (let i = 0, len = res.data.length; i < len; i++){
          res.data[i].value = res.data[i].hosname
        }
        cb(res.data)
      })
    },
    // 绑定登录，点击显示登录层
    showLogin() {
      this.dialogUserFormVisible = true
      // 初始化登录层相关参数
      this.dialogAttr = { ...defaultDialogAttr }

    },
    // 关闭登录
    closeDialog() {
      if(this.clearSmsTime) {
        clearInterval(this.clearSmsTime)
      }
    },
    // 获取验证码
    getCodeFun() {
      if(!(/^1[34578]\d{9}$/.test(this.userInfo.phone))){
        this.$message.error('手机号不正确')
        return
      }
      // 初始化验证码相关属性
      this.dialogAttr.inputValue = ''
      this.dialogAttr.placeholder = '请输入验证码'
      this.dialogAttr.maxlength = 6
      this.dialogAttr.loginBtn = '马上登录'
      // 控制重复登录
      if(!this.dialogAttr.sending){
        return
      }
      // 发送短信验证码
      this.timeDown()
      this.dialogAttr.sending = false
      msm.sendCode(this.userInfo.phone).then(res => {
        this.timeDown()
      }).catch(err => {
        this.$message.error('发送失败，请重新发送')
        this.showLogin()
      })
    },
    // 倒计时功能
    timeDown() {
      if(this.clearSmsTime) {
        clearInterval(this.clearSmsTime)
      }
      this.dialogAttr.second = 60
      this.dialogAttr.labelTips = '验证码已发至' + this.userInfo.phone
      this.clearSmsTime = setInterval(() => {
        --this.dialogAttr.second
        if(this.dialogAttr.second < 1) {
          clearInterval(this.clearSmsTime)
          this.dialogAttr.sending = true
          this.dialogAttr.second = 0
        }
      }, 1000)
    },
    // 登录
    login() {
      this.userInfo.code = this.dialogAttr.inputValue
      if (this.dialogAttr.loginBtn === '正在提交...') {
        this.$message.warning('重复提交')
        return
      }
      if(this.userInfo.code === ''){
        this.$message.error('验证码必须输入')
        return
      }
      if(this.userInfo.code.length !== 6) {
        this.$message.error("验证码格式不正确")
        return
      }
      this.dialogAttr.loginBtn = '正在提交...'
      userInfo.login(this.userInfo).then(res => {
        // 设置cookie
        this.setCookies(res.data.name, res.data.token)
      }).catch(err => {
        this.dialogAttr.loginBtn = '马上登录'
      })
    },
    // 设置cookies
    setCookies(name, token){
      cookie.set('token', token, { domain: 'localhost'})
      cookie.set('name', name, { domain: 'localhost'})
      window.location.reload()
    },
    // 获取显示信息
    showInfo() {
      let token = cookie.get('token')
      if(token) {
        this.name = cookie.get('name')
      }
    },
    // 切换登出
    loginMenu(command) {
      if('/logout' === command){
        cookie.set("name", '', {domain: 'localhost'})
        cookie.set("token", '', {domain: 'localhost'})

        // 跳转页面
        window.location.href = '/'
      }else {
        window.location.href = command
      }
    },
    handleSelect(item){
      window.location.href = '/hospital/' + item.hoscode
    },
    // 登录微信回调处理
    loginCallback(name, token, openid) {
      // 打开手机登录层，绑定手机号
      if(openid !== ''){
        this.userInfo.openid = openid
        this.showLogin()
      }else {
        this.setCookies(name, token)
      }
    },
    // 微信登录
    weixinLogin() {
      this.dialogAttr.showLoginType = 'weixin'
      wechat.getLoginParam().then(res => {
        console.log(res)
        let obj = new WxLogin({
          self_redirect: true,
          id: 'weixinLogin', // 需要显示的容器id
          appid: res.data.appid, // 公众号appid wx*******
          scope: res.data.scope, // 网页默认即可
          redirect_uri: res.data.redirectUri, // 授权成功后回调的url
          state: res.data.state, // 可设置为简单的随机数加session用来校验
          style: 'black', // 提供"black"、"white"可选。二维码的样式
          href: '' // 外部css文件url，需要https
        })
      })
    },
    // 手机登录
    phoneLogin() {
      this.dialogAttr.showLoginType = 'phone'
      this.showLogin()
    }
  }
}
</script>

<style scoped>

</style>
